package jwebtester.business.beans;

import jwebtester.business.services.LoginService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component
@Scope("request")
public class LoginBean {

	private String userName;

	private String password;

	@Autowired
	private transient LoginService loginService;

	public String login() {
		String result = "loggedIn";
		try {
			final Authentication authResult = loginService.authenticate(getUserName(), getPassword());
			SecurityContextHolder.getContext().setAuthentication(authResult);

		} catch (RuntimeException e) {
			result = "accessDenied";
		}
		
		return result;
	}

	public String logout() {
		loginService.logout();
		return "loggedOut";
	}

	public String cancel() {
		return null;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(final String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(final String password) {
		this.password = password;
	}
}